package com.cykj.util;

import com.cykj.entity.FileDO;
import com.cykj.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.UUID;

/**
 * @Program: Mooc-Admin
 * @Package: com.cykj.util
 * @Author: 张俊杰
 * @Create: 2025-07-09 11:44
 * @Description: TODO
 * @Vision: 1.0
 **/
@Component
public class FileUploadUtil {

    @Value("${upload}")
    private String uploadPath;

    @Value("${baseUrl}")
    private String baseUrl;

    @Autowired
    private FileMapper fileMapper;


    /**
     * @Description:文件上传
     * @Param:[file]返回相对路径
     * @Return:java.lang.String
     */
    public String uploadFile(MultipartFile file) {

        try {
            if (file.isEmpty()) {
                return "上传的文件为空";
            }

            InputStream inputStream = file.getInputStream();
            String hash = DigestUtils.md5DigestAsHex(inputStream);

            FileDO fileInfo = fileMapper.getFile(hash);

            if (fileInfo != null) {
                return fileInfo.getFileUrl();
            }

            // 获取文件 MIME 类型和扩展名
            String contentType = file.getContentType();
            String[] splitContentType = contentType.split("/");
            String fileType = splitContentType[0];  // "image" 或 "video"

            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(
                    originalFilename.lastIndexOf(".") + 1
            ).toLowerCase();

            // 校验文件扩展名是否合法
            if (!isValidExtension(fileType, fileExtension)) {
                throw new IllegalArgumentException("文件类型和扩展名不匹配！");
            }

            // 确定存储的子目录（images/videos/...）
            String subDir;
            if (fileType.equals("image")) {
                subDir = "images";
            } else if (fileType.equals("video")) {
                subDir = "videos";
            } else {
                subDir = "others";
            }

            // 创建目标目录（如果不存在）
            File targetDir = new File(uploadPath + subDir);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }

            // 生成随机文件名
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String newFilename = uuid + "." + fileExtension;

            // 存储文件
            File destFile = new File(targetDir, newFilename);
            file.transferTo(destFile);

            String relativePath = subDir + "/" + newFilename;
            String fileURL = baseUrl + relativePath;

            // 存储文件到数据库当中
            FileDO fileDO = new FileDO(newFilename, hash, file.getSize(), fileType, relativePath, fileURL);
            fileMapper.addFile(fileDO);

            // 返回相对路径（如 images/xxx.jpg）
            return fileURL;
        } catch (IOException e) {
            throw new RuntimeException("文件存储失败: " + e.getMessage(), e);
        }
    }

    /**
     * 校验文件扩展名是否合法
     */
    private boolean isValidExtension(String fileType, String extension) {
        if (fileType.equals("image")) {
            return Arrays.asList("jpg", "jpeg", "png", "gif", "webp").contains(extension);
        } else if (fileType.equals("video")) {
            return Arrays.asList("mp4", "webm", "avi", "mov", "mkv").contains(extension);
        }
        return false;
    }

    //private String
}
